package com.ry.framework.mongo.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import com.mongodb.Mongo;
import com.ry.framework.mongo.bean.Topic;

/**
 * mongodb 增删改示例
 * 还需继续优化
 */
@Component
public class MongoService {

	@Autowired
	private MongoTemplate mongoTemplate;
	
	//条件查询
	public Topic findOne(){
		Query q = new Query(Criteria.where("empid").is(10));
//		Query q = new Query(Criteria.where("id").is("5c9edab368b7961f44153c18"));
		Topic t =  mongoTemplate.findOne(q , Topic.class, "emp");
		return t;
	}

	//查询所有
	public List<Topic> findAll(){
		List<Topic> list =  mongoTemplate.findAll(Topic.class, "emp");
		return  list;
	}
	
	//保存对象
	public String save(Topic t){
		mongoTemplate.save(t, "emp");
		return  "保存成功";
	}
	
	//修改对象
	public String update(Topic t) {
		Query query = new Query(Criteria.where("empid").is(t.getEmpid()));
		Update update = new Update()
				.set("ename", "哈哈")
				.set("dev", "开发");
		
		//updateFirst 更新查询返回结果集的第一条
		mongoTemplate.updateFirst(query, update, Topic.class, "emp");
		//updateMulti 更新查询返回结果集的全部
		//mongoTemplate.updateMulti(query,update,Topic.class);
		//upsert 更新对象不存在则去添加
		//mongoTemplate.upsert(query,update,Topic.class);
		return "修改完成";
	}
	
	//删除对象
	public String delete() {
		Query query = new Query(Criteria.where("empid").is(10));
		mongoTemplate.remove(query, Topic.class, "emp");
		return "success";
	}
	
}
